package cn.fntop.entity;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.MD5;
import lombok.*;

/**
 * @author fn
 * @description
 * @date 2023/8/6 2:57
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SmsRequest {
    private String appId;
    // appSecret
    private String appSecret;
    private int sid;
    private int templateId;
    private String phone;
    /**
     * 模板替换数据  模板（验证码{code}，{ttl}分钟内有效。您正在登录，如非本人操作，请忽略本短信。）
     * data => "data": {
     * "{code}":"7859",
     * "{ttl}":"60"
     * }
     */
    private Dict data;
    /**
     * 加密传输参数
     */
    private Long timestamp;
    private String nonce;
    private String sign;


    public SmsRequest sign() {
        if (timestamp == null && nonce == null && sign == null && appSecret != null) {
            long currentTimeMillis = System.currentTimeMillis();
            String nonce = RandomUtil.randomString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 10);
            this.timestamp = currentTimeMillis;
            this.nonce = nonce;
            StringBuilder bf = new StringBuilder();
            bf.append("appId=").append(appId);
            bf.append("&phone=").append(phone);
            bf.append("&timestamp=").append(this.timestamp);
            bf.append("&nonce=").append(this.nonce);
            bf.append("&secretKey=").append(appSecret);
            this.sign = MD5.create().digestHex(bf.toString());
        }
        //置空appSecret,防止泄秘钥
        this.appSecret = null;
        return this;
    }
}
